#!/usr/bin/env luajit
-- -*- lua -*-

package.path = package.path .. ";../src/?.lua"

local pf = require("pf")
local bpf = require("pf.bpf")
local match = require("pf.match")
local utils = require("pf.utils")

function usage()
   local content = [=[
Usage: pflua-compile [-O0] [--bpf-asm | --bpf-lua | --lua | --native | --match] <expression>

Options:
   --bpf-asm   Print libpcap-generated BPF asm code for the pflang <expression>
   --bpf-lua   Print Lua code compiled from BPF for the pflang <expression>
   --lua       Print Lua code compiled directly for the pflang <expression> (DEFAULT)
   --native    Print dynasm-generated asm code for the pflang <expression>
   --match     Print Lua code compiled from the pfmatch <expression>

   -O0         Disable optimizations. (Optimizations are on by default) ]=]
   print(content);
   os.exit()
end

-- Print help
if #arg == 0 then
   usage()
end

local flags = utils.set(...)

-- Print help
if flags["--help"] or flags["-h"] then
   usage()
end

-- No code-generation flag defined
if (not(flags["--bpf-asm"] or flags["--bpf-lua"] or flags["--lua"] or flags["--native"] or flags['--match'])) then
   -- Default action
   flags["--lua"] = true
end


local optimize = true
if flags["-O0"] then optimize = false end

local filter = arg[#arg]
if flags["--bpf-asm"] then
   print(pf.compile_filter(filter, {libpcap=true, source=true,
                                    optimize=optimize}))
end
if flags["--bpf-lua"] then
   print(pf.compile_filter(filter, {bpf=true, source=true,
                                    optimize=optimize}))
end
if flags["--lua"] then
   print(pf.compile_filter(filter, {source=true, optimize=optimize}))
end
if flags["--native"] then
   print(pf.compile_filter(filter, {native=true, source=true, optimize=optimize}))
end
if flags["--match"] then
   print(match.compile(filter, {source=true, optimize=optimize}))
end
